package tech.aistar.day07.homework;

import java.util.Arrays;

/**
 * 本类用来演示:
 *
 * @author: success
 * @date: 2021/3/17 8:36 上午
 */
public class BookBizImpl implements IBookBiz{

    //模拟的就是未来的DB数据库
    //使用数组充当DB的角色
    private static final int CAPACITY = 5;
    private int count; //代表有效图书数量
    private Book[] books = new Book[CAPACITY];

    @Override
    public void add(Book b) {
        if(count == books.length){
            //扩容操作...
            //System.out.println("开始进行扩容...");
            books = Arrays.copyOf(books,books.length+CAPACITY);
        }
        books[count++] = b;
    }

    @Override
    public void deleteByName(String name) {
        //假设名称是重复的...
        //统计name出现的次数.
        int pos = 0;
        for (int i = 0; i < count; i++) {
            if(books[i].getBookName().equals(name)){
                pos++;
            }
        }
        //判断是否存在
        if(pos == 0){
            System.out.println("名称为"+name+"的图书不存在!");
            return;
        }
        //确定一个新的数组
        Book[] temp = new Book[count-pos];

        //定义下标计数器
        int index = 0;
        for (int i = 0; i < count; i++) {
            if(!books[i].getBookName().equals(name)){
                temp[index++] = books[i];
            }
        }
        books = temp;
        count = index;
    }

    @Override
    public void outputAllBooks() {
        if(count!=0){
            for (int i = 0; i < count; i++) {
                System.out.println(books[i]);
            }
        }
    }
}
